package com.wondertek.mam.tag.config;

import com.google.common.base.Charsets;
import com.wondertek.mam.tag.repository.TagRepository;
import com.wondertek.mam.tag.service.TagService;
import com.wondertek.mam.tag.wordSource.WordSource;
import org.apache.commons.io.IOUtils;
import org.apdplat.word.dictionary.DictionaryFactory;
import org.apdplat.word.util.AutoDetector;
import org.apdplat.word.util.DirectoryWatcher;
import org.apdplat.word.util.ResourceLoader;
import org.apdplat.word.util.WordConfTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * Created by wangdongxu on 2017-09-12 下午 17:39:56.
 */
@Component
public class ScheduleTask {
    private static final Logger LOGGER = LoggerFactory.getLogger(ScheduleTask.class);

    public static boolean refreshFlag = false;
    @Autowired
    private List<WordSource> wordSources;

    @Autowired
    private TagService tagService;

    @Autowired
    private TagRepository tagRepository;

    @Autowired
    private ApplicationProperties applicationProperties;
    @Scheduled(cron = "0 0 2 * * ?")
    public void getWords() {
        LOGGER.info("词库刷新开始...");
        LOGGER.info("更新词库...");
        wordSources.parallelStream().forEach(WordSource::getAndSaveHotWords);
        LOGGER.info("更新权重和热词标记...");
        tagService.delHotFlag(LocalDate.now().atStartOfDay());
        tagService.updateScore(LocalDate.now().minusMonths(1L).atStartOfDay(), LocalDate.now().minusWeeks(1L).atStartOfDay(), 3);//一周期到一个月
        tagService.updateScore(LocalDate.now().minusMonths(3L).atStartOfDay(), LocalDate.now().minusMonths(1L).atStartOfDay(), 2);//一个月到三个月
        tagService.updateScore(LocalDate.now().minusMonths(3L).atStartOfDay(), 1);//三个月到半年
        refreshWord();
        LOGGER.info("词库刷新结束...");
    }


    @Scheduled(cron = "0 0/10 0,1,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23 * * ?")
    public void refresh(){
        if (refreshFlag){
            refreshFlag = false;
            refreshWord();
        }

    }
    private void refreshWord(){
        LOGGER.info("输出词库文件...");
        File thesaurusFile = new File(applicationProperties.getThesaurusFile());
        if (!thesaurusFile.exists()) {
            mkDir(thesaurusFile.getParentFile());
        }
        try {
            FileOutputStream fos = new FileOutputStream(thesaurusFile);
            tagRepository.findAll().parallelStream().forEach(tagDB -> {
                try {
                    IOUtils.write(tagDB.getTag() + "\r", fos, Charsets.UTF_8);
                } catch (IOException e) {
                    LOGGER.error("写入词库文件时出错(tag:" + tagDB.getTag() + ").");
                    e.printStackTrace();
                }
            });
        } catch(FileNotFoundException e){
            LOGGER.error("创建词库文件时出错");
            e.printStackTrace();
        }
        LOGGER.info("刷新分词字典...");
        synchronized (Constant.class) {
            synchronized (AutoDetector.class) {
                WordConfTools.set("dic.path", applicationProperties.getThesaurusFile());
                WordConfTools.reload();
            }
            try {
                Thread.sleep(500L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    private static void mkDir(File file) {
        if (file.getParentFile().exists()) {
            file.mkdir();
        } else {
            mkDir(file.getParentFile());
            file.mkdir();
        }
    }
}
